<template>
  <div id="pushedList">
    <el-card class="box-card">
      <!--<div slot="header" class="clearfix">-->
      <h4 class="textItem">
        推送信息
      </h4>
      <!--</div>-->
      <div class="info-item">
        <div>
          <span class="tipText">推送名称 : </span><span>{{costomer.folderName}}</span>
        </div>
        <div class="lastItem">
          <span class="tipText">重单数 : </span><span>{{costomer.repeatCount}}</span>
        </div>
      </div>
      <div class="info-item">
        <div>
          <span class="tipText">目标机构 : </span><span>{{!!costomer.orgName ? costomer.orgName : '-' }}</span>
        </div>
        <div>
          <span class="tipText">行业 : </span><span>{{costomer.industryName}}</span>
        </div>
      </div>
      <div class="info-item">
        <div>
          <span class="tipText">推送数量 : </span><span>{{costomer.pushCount}}</span>
        </div>
        <div>
          <span class="tipText">状态 : </span><span>{{ checkStatus[costomer.checkStatus] }}</span>
        </div>
      </div>
      <div class="info-item">
        <div>
          <span class="tipText">推送时间 : </span><span>{{costomer.PushTime}}</span>
        </div>
      </div>
    </el-card>

    <router-link :to="{path:'/pushed/waitList'}">
      <div class="listCart fa fa-th-list">
        <i class="num">{{waitListCount}}</i>
      </div>
    </router-link>

    <div class="select-box" style="margin: 25px 0;">
      <div class="select-group">
        <div class="items">
          <span class="items-text">是否重单</span>
          <el-select v-model="query.isRepeat" clearable placeholder="请选择">
            <el-option
              v-for="item in repeatList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="items">
          <span class="items-text">有效沟通</span>
          <el-select v-model="query.isCommunicate" clearable placeholder="请选择">
            <el-option
              v-for="item in communicateList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="select-group">
        <div class="items">
          <span class="items-text">预约到店</span>
          <el-select v-model="query.isArrival" clearable placeholder="请选择">
            <el-option
              v-for="item in arrivalList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="items">
          <span class="items-text">成交情况</span>
          <el-select v-model="query.isBargain" clearable placeholder="请选择">
            <el-option
              v-for="item in barginList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="select-group">
        <div class="items">
          <span class="items-text">营销建议</span>
          <el-select v-model="query.advice" clearable placeholder="请选择">
            <el-option
              v-for="item in adviceList"
              :key="item.adviceId"
              :label="item.adviceName"
              :value="item.adviceId">
            </el-option>
          </el-select>
        </div>
        <div class="items">
          <el-button :disabled="listLoading" @click="getList" size="medium" type="success"
                     class="el-icon-search searchBtn">
            <span style="padding-left:5px;">查询</span>
          </el-button>
        </div>
      </div>
    </div>

    <div style="text-align: right;width: 90%;margin-bottom: 25px;">
      <el-button @click="addWaitList" size="medium" type="success" class="searchBtn">
        <span style="padding-left:5px;">加入待转列表</span>
      </el-button>
    </div>

    <el-dialog
      class="imgBoxDialog"
      :visible.sync="img_Visible"
      :width="img_width"
    >
      <img style="width: 100%" :src="repeatImgaeUrl" alt="">
    </el-dialog>

    <el-dialog width="400px"
    title="编辑呼叫记录"
    :visible.sync="callVisible"
    @close="cancledialog('callForm')"
    >
    <el-form :model="itemRowData"  :rules="rulesCall" ref="callForm">
    <el-form-item prop="phone"
    label="手机号码"
    :label-width="formLabelWidth">
    <el-input style="width: 200px;" v-model.sync="itemRowData.phone" placeholder="请输入"></el-input>
    </el-form-item>
    <el-form-item
    label="意向项目"
    :label-width="formLabelWidth">
    <el-input style="width: 200px;" v-model.sync="itemRowData.item"  placeholder="请输入意向项目"></el-input>
    </el-form-item>
    <el-form-item
    label="客服备注"
    :label-width="formLabelWidth">
    <el-input style="width: 200px;" type="textarea" :autosize="{ minRows:3,maxRows:5 }"  v-model.sync="itemRowData.remarks"  placeholder="请输入备注"></el-input>
    </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
    <el-button type="primary" size="mini" @click="pushUpdate">确定</el-button>
    <el-button @click="callVisible = false" size="mini">取 消</el-button>
    </div>
    </el-dialog>

    <el-table @selection-change="handleSelectionChange"
              class="pushTable"
              empty-text="暂无任何用户信息"
              :data="list"
              v-loading.body="listLoading"
              border
              fit
              style="width: 100%">
      <el-table-column
        align="center"
        type="selection"
        width="40">
      </el-table-column>
      <el-table-column align="center" label="数据ID">
        <template slot-scope="scope">
          <span>{{ scope.row.customerName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="电话">
        <template slot-scope="scope">
          <span>{{ !!scope.row.phone ? scope.row.phone : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="微信">
        <template slot-scope="scope">
          <span>{{!!scope.row.wechat ? scope.row.wechat : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="客服备注">
        <template slot-scope="scope">
          <span>{{!!scope.row.remarks ? scope.row.remarks : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="营销建议" width="125">
        <template slot-scope="scope">
          <el-select v-model="scope.row.adviceCode" @change="adviceChange(scope.row)" placeholder="请选择">
            <el-option
              style="height: 35px"
              v-for="item in adviceList"
              :key="item.adviceId"
              :label="item.adviceName"
              :value="item.adviceId">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否重单">
        <template slot-scope="scope">
          <span>{{ scope.row.isRepeat != 1 ? ( scope.row.isRepeat == 2 ? '重单' : '未重单') : '-' }}</span>
          <div v-if="scope.row.isRepeat == 2" @click="showImage(scope.row.image)" style="color:#409EFF;cursor: pointer">查看图片</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="有效沟通">
        <template slot-scope="scope">
          <span>{{ !!scope.row.isCommunicate ? ( scope.row.isCommunicate == 1  ? '已沟通' : '未沟通') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="预约到店">
        <template slot-scope="scope">
          <span>{{ !!scope.row.isArrival ? ( scope.row.isArrival == 1  ? '已到店' : '未到店') : '-'  }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="成交情况">
        <template slot-scope="scope">
          <span>{{ !!scope.row.isBargain ? ( scope.row.isBargain == 1 ? '已成交' : '未成交') : '-'   }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="成交项目">
        <template slot-scope="scope">
          <span>{{ !!scope.row.deal  ? scope.row.deal : '-'  }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="金额(元)">
        <template slot-scope="scope">
          <span>{{ !!scope.row.money ? scope.row.money : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="机构备注">
        <template slot-scope="scope">
          <span>{{ !!scope.row.feedbackRemarks ? scope.row.feedbackRemarks : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="220">
          <template slot-scope="scope">
            <router-link @click.native="saveLocal(scope.row)"  style="margin-right: 9px;" :to="{path:'/datapush/detail'}">
              <el-button type="primary" size="small" >详情</el-button>
            </router-link>
            <el-button  @click="openCallDialog(scope.row)"  type="success" size="small" >编辑</el-button>
          </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background
                     @size-change="handleSizeChange"
                     prev-text="上一页"
                     next-text="下一页"
                     @current-change="handleCurrentChange"
                     :current-page="query.current"
                     :page-sizes="[10,20,30,50]"
                     :page-size="query.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import {getPushedDetailList,updatePushAdvice,getWaitList,addWaitList ,pushUpdate} from '@/api/datapush'

  import { mapGetters } from 'vuex';

  import {filterObj} from "@/utils/index";

  export default {
    name: "pushed-list",
    data() {
      const isPhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入手机号码'));
        } else if (value.length != 11) {
          callback(new Error('请输入正确的手机号码'));
        } else{
          callback();
        }
      }
      return {
        itemRowData:{},
        formLabelWidth:'120px',
        repeatImgaeUrl:'',
        img_width:'',
        img_Visible:false,
        waitListCount:'',
        callVisible:false,
        checkStatus: {1: '未接收', 2: '审查中', 3: '已接收'},
        listLoading: false,
        total: 0,
        list: [],
        multipleSelection: [], //列选中的列id
        costomer: {},
        rulesCall:{
          phone:[
            {validator:isPhone, trigger: 'blur'},
          ]
        },
        query: {
          isRepeat: '',
          isCommunicate: '',
          isArrival: '',
          isBargain: '',
          current: 1,
          pagesize: 10,
        },
        repeatList: [
          {id: '2', name: '重单'},
          {id: '3', name: '未重单'},
        ],
        adviceList: [
          {adviceId: 1, adviceName: '可跟进'},
          {adviceId: 2, adviceName: '需等待'},
        ],
        barginList: [
          {id: '1', name: '已成交'},
          {id: '2', name: '未成交'},
        ],
        arrivalList: [
          {id: '1', name: '已到店'},
          {id: '2', name: '未到店'},
        ],
        communicateList: [
          {id: '1', name: '已沟通'},
          {id: '2', name: '未沟通'},
        ],
      }
    },

    created(){
        if(this.userInfo.roleId == 1 && !this.userInfo.companyId){
          this.$message.error('当前身份没有companyId,请去首页设置临时公司身份');
        } else {
          this.getPustCount();
          this.fetchData();
        }
    },
    watch: {
      // 如果路由有变化，会再次执行该方法
      '$route'(to,from){
        if(to.path === '/pushed/pushedlist'){
          if(this.userInfo.roleId == 1 && !this.userInfo.companyId){
            this.$message.error('当前身份没有companyId,请去首页设置临时公司身份');
          } else {
            this.getPustCount();
            this.fetchData();
          }
        }
      }
    },
    computed:{
      ...mapGetters([
        'userInfo'
      ])
    },
    methods: {
      showImage(url){
        let maxWidth = Math.floor(window.innerWidth * 0.8);
        let img = new Image();
        img.src = url;
        img.onload = ()=>{
          this.img_width = (img.width > maxWidth ? maxWidth : img.width ) + 'px';
          this.repeatImgaeUrl = url;
          this.img_Visible = true;
        }
      },
      getPustCount(){
        getWaitList({companyId:this.userInfo.companyId}).then(res=>{
          this.waitListCount = res.data.total;
        }).catch(res=>{
          this.$message.error(res);
        })
      },
      addWaitList(){
        if(this.waitListCount * 1 >= 2000){
          this.$message.warning('待转列表最多一次推送2000条,请推送后在进行添加');
          return;
        }
        let temp = {
          folderId:this.query.folderId,
          orgId:this.query.orgId,
          companyId:this.userInfo.companyId,
          customerId:this.multipleSelection
        }

        addWaitList(temp).then(res=>{
          this.$message.success(res.msg)
          this.waitListCount = res.data.total;
          this.getList();
        }).catch(res=>{
          this.$message.error(res);
        })
      },
      adviceChange(val){
         let temp = this.filterObj(val,['adviceCode','customerId']);
         temp['folderId'] = this.query.folderId;
         temp['orgId'] = this.query.orgId;
         updatePushAdvice(temp).then(res=>{
           this.$message.success(res.msg);
         }).catch(res=>{
           this.$message.error(res);
         })
      },
      fetchData() {
        this.list = [];
        let thisUserInfo = JSON.parse(localStorage.getItem('PUSHED_DATA'));
        this.costomer = thisUserInfo;
        this.query.folderId = thisUserInfo.folderId;
        this.query.orgId = thisUserInfo.orgId;
        this.query.companyId = this.userInfo.companyId;  //新加参数 ，文档上没有
        this.getList();
      },
      getList() {
        let temp = this.filterObj(this.query);
        this.listLoading = true;
        getPushedDetailList(temp).then(response => {
          const temp = response.data;
          this.total = temp.total;
          this.list = temp.info;
          this.list[0]['isFirst'] = true;
          this.listLoading = false;
        }).catch(res => {
          this.listLoading = false
          this.$message.error(res)
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val.map(v => v.customerId);
      },
      handleSizeChange(val) {
        this.query.pagesize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.query.current = val;
        this.getList();
      },
      pushUpdate(){
        this.$refs.callForm.validate(valid=> {
          if (!valid) {
            return
          }

          let tar_rowData = JSON.parse(JSON.stringify(this.itemRowData));
          let temp = {
            customerId:tar_rowData.customerId,
            phone:tar_rowData.phone,
            item:tar_rowData.item,
            // callTime:tar_rowData.callTime,
            remarks:tar_rowData.remarks
          }
          pushUpdate(temp).then(res=>{
            this.callVisible = false;
            this.$message.success({message:res.msg,duration:1000,onClose:()=>{
                this.getList();
              }})
          }).catch(res=>{
            this.callVisible = false;
            this.$message.error(res)
          })
        })

      },
      cancledialog(userForm) {
        //重置表单
        this.$refs[userForm].resetFields();
      },
      openCallDialog(rowData){
          this.itemRowData = JSON.parse(JSON.stringify(rowData));
          this.callVisible =  true;
        },
      saveLocal(item){
        let local_user = localStorage.getItem('PUSH_DATA');
        !!local_user ? localStorage.removeItem('PUSH_DATA') : null;
        localStorage.setItem('PUSH_DATA',JSON.stringify(item))
      },
      filterObj
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  #pushedList {
    .listCart {
      cursor: pointer;
      z-index: 1000;
      position: fixed;
      right: 15%;
      bottom: 5%;
      width: 80px;
      height: 80px;
      border-radius: 50%;
      display: inline-block;
      background-color: #ccc;
      text-align: center;
      font-size: 50px;
      line-height: 80px;
      color: #eee;
      i {
        position: absolute;
        right: 1px;
        font-style: normal;
        display: inline-block;
        width: 26px;
        height: 26px;
        background-color: red;
        color: #fff;
        text-align: center;
        line-height: 26px;
        font-size: 14px;
        border-radius: 50%;
      }
    }
    .searchBtn {
      margin-left: 30px;
    }
    .info-item {
      margin: 25px 0px 25px 50px;
      > div {
        display: inline-block;
        min-width: 320px;
      }
      > div.lastItem {
        margin-top: 25px;
      }
      .tipText {
        display: inline-block;
        margin-right: 10px;
        min-width: 100px;
        text-align: right;
      }
    }
  }
</style>
